package cn.itcast.user.service.impl;

import cn.itcast.user.mapper.UserMapper;
import cn.itcast.user.param.user.UserRegisterParam;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import cn.itcast.user.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static cn.itcast.user.util.MD5Util.md5;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    public UserVO queryById(Long id) {
        return null;
    }

    public User queryUserByAccount(String account) {
        return null;
    }

    @Override
    public Boolean addUser(UserRegisterParam user) {
        // 查询account是否已存在
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda();
        queryWrapper.eq(User::getAccount, user.getAccount());
        Integer userCount = userMapper.selectCount(queryWrapper);
        if (userCount > 0) {
            return false;
        }
        String salt = UUID.randomUUID().toString();
        String passWord = md5(user.getPassword(), salt);
        User insertUser = new User(user.getAccount(), passWord, salt, user.getUsername(), user.getAddress());
        return userMapper.insertUser(insertUser);
    }

    @Override
    public User doUserLogin(String account, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        User selectedUser = userMapper.selectOne(queryWrapper);
        if (selectedUser == null) {
            return null;
        }
        String salt = selectedUser.getSalt();
        String md5Word = md5(password, salt);
        if (md5Word.equals(selectedUser.getPassword())) {
            return selectedUser;
        }
        return null;
    }

}
